<template>
  <div class="admin-user-container">
    <div class="page-header">
      <el-button type="primary" icon="el-icon-plus" @click="addUser">添加用户</el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-container">
      <el-input
        placeholder="请输入用户名或邮箱搜索"
        v-model="searchText"
        class="search-input"
        clearable
        prefix-icon="el-icon-search"
        @clear="fetchUsers"
        @keyup.enter.native="handleSearch"
      ></el-input>
      <el-button type="primary" @click="handleSearch" icon="el-icon-search">搜索</el-button>
      <el-button @click="resetSearch" icon="el-icon-refresh">重置</el-button>
    </div>

    <!-- 用户表格 -->
    <el-table
      :data="userList"
      style="width: 100%"
      border
      v-loading="loading"
      element-loading-text="加载中..."
      stripe
      highlight-current-row
    >
      <el-table-column prop="userId" label="ID" width="80" align="center"></el-table-column>
      <el-table-column label="头像" width="100" align="center">
        <template slot-scope="scope">
          <el-avatar 
            size="medium" 
            :src="scope.row.avatarUrl" 
            @error="() => true">
            <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"/>
          </el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名" align="center"></el-table-column>
      <el-table-column prop="emali" label="邮箱" align="center"></el-table-column>
      <el-table-column prop="createdAt" label="创建时间" align="center" width="180">
        <template slot-scope="scope">
          <span>{{ formatDate(scope.row.createdAt) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220" align="center">
        <template slot-scope="scope">
          <el-button 
            @click="viewUserDetail(scope.row.userId)" 
            type="text" 
            size="small" 
            icon="el-icon-view">
            查看
          </el-button>
          <el-button 
            @click="editUser(scope.row)" 
            type="text" 
            size="small" 
            icon="el-icon-edit">
            编辑
          </el-button>
          <el-button 
            @click="showDeleteConfirm(scope.row)" 
            type="text" 
            size="small" 
            class="danger-text" 
            icon="el-icon-delete">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      class="pagination"
    ></el-pagination>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="form" :rules="rules" ref="userForm" label-width="100px">
        <el-form-item label="头像" class="avatar-uploader-container">
          <el-upload
            class="avatar-uploader"
            action="/file/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeUpload">
            <img v-if="form.avatarUrl" :src="form.avatarUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="passwordHash" v-if="!form.userId">
          <el-input v-model="form.passwordHash" type="password" placeholder="请输入密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="passwordHash" v-else>
          <el-input v-model="form.passwordHash" type="password" placeholder="不修改请留空" show-password></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="emali">
          <el-input v-model="form.emali" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="form.sex">
            <el-radio :label="true">男</el-radio>
            <el-radio :label="false">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="出生日期">
          <el-date-picker
            v-model="form.age"
            type="date"
            placeholder="选择日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="个人简介">
          <el-input v-model="form.bio" type="textarea" :rows="2" placeholder="请输入个人简介"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remarks" placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveUser" :loading="submitLoading">保存</el-button>
      </span>
    </el-dialog>

    <!-- 用户详情对话框 -->
    <el-dialog title="用户详情" :visible.sync="detailDialogVisible" width="500px">
      <div v-if="userDetail" class="user-detail">
        <div class="user-avatar-container">
          <el-avatar 
            size="large" 
            :src="userDetail.avatarUrl" 
            @error="() => true">
            <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"/>
          </el-avatar>
        </div>
        <div class="detail-item">
          <span class="detail-label">用户ID：</span>
          <span class="detail-value">{{ userDetail.userId }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">用户名：</span>
          <span class="detail-value">{{ userDetail.username }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">邮箱：</span>
          <span class="detail-value">{{ userDetail.emali }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">性别：</span>
          <span class="detail-value">{{ userDetail.sex ? '男' : '女' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">年龄：</span>
          <span class="detail-value">{{ calculateAge(userDetail.age) }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">个人简介：</span>
          <span class="detail-value">{{ userDetail.bio || '暂无' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">备注：</span>
          <span class="detail-value">{{ userDetail.remarks || '暂无' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">创建时间：</span>
          <span class="detail-value">{{ formatDate(userDetail.createdAt) }}</span>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      userList: [], // 用户列表数据
      loading: false, // 加载状态
      dialogVisible: false, // 对话框显示状态
      detailDialogVisible: false, // 详情对话框显示状态
      dialogTitle: '', // 对话框标题
      submitLoading: false, // 提交按钮加载状态
      page: 1, // 当前页码
      pageSize: 10, // 每页条数
      total: 0, // 总条数
      searchText: '', // 搜索关键字
      userDetail: null, // 用户详情
      form: {
        userId: null,
        username: '',
        passwordHash: '',
        emali: '',
        avatarUrl: '',
        bio: '',
        sex: true,
        age: '',
        remarks: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        passwordHash: [
          { required: function(form) { return !form.userId; }, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        emali: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '暂无记录';
      const date = new Date(dateString);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
    },
    
    // 处理头像上传成功
    handleAvatarSuccess(res) {
      if (res.code === 1 && res.data) {
        this.form.avatarUrl = `/file/download?fileUuid=${res.data}`;
      } else {
        this.$message.error('上传失败');
      }
    },
    
    // 上传图片前的验证
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        this.$message.error('只能上传图片文件！');
        return false;
      }
      return true;
    },
    
    // 添加用户
    addUser() {
      this.dialogTitle = '添加用户';
      this.form = {
        userId: null,
        username: '',
        passwordHash: '',
        emali: '',
        avatarUrl: '',
        bio: '',
        sex: true,
        age: '',
        remarks: ''
      };
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.userForm && this.$refs.userForm.clearValidate();
      });
    },
    
    // 编辑用户
    editUser(user) {
      this.dialogTitle = '编辑用户';
      this.form = { 
        userId: user.userId,
        username: user.username,
        passwordHash: '', // 编辑时密码为空，表示不修改
        emali: user.emali,
        avatarUrl: user.avatarUrl,
        bio: user.bio || '',
        sex: user.sex,
        age: user.age,
        remarks: user.remarks || ''
      };
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.userForm && this.$refs.userForm.clearValidate();
      });
    },
    
    // 保存用户信息
    saveUser() {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          if (this.form.userId) {
            // 更新用户
            this.request.put(`/users/admin/update/${this.form.userId}`, this.form)
              .then(res => {
                if (res.code === 1) {
                  this.$message.success('更新成功');
                  this.dialogVisible = false;
                  this.fetchUsers();
                } else {
                  this.$message.error(res.msg || '更新失败');
                }
              })
              .catch(error => {
                console.error('更新用户失败:', error);
                this.$message.error('更新用户失败');
              })
              .finally(() => {
                this.submitLoading = false;
              });
          } else {
            // 创建用户
            this.request.post('/users/admin/create', this.form)
              .then(res => {
                if (res.code === 1) {
                  this.$message.success('添加成功');
                  this.dialogVisible = false;
                  this.fetchUsers();
                } else {
                  this.$message.error(res.msg || '添加失败');
                }
              })
              .catch(error => {
                console.error('添加用户失败:', error);
                this.$message.error('添加用户失败');
              })
              .finally(() => {
                this.submitLoading = false;
              });
          }
        } else {
          return false;
        }
      });
    },
    
    // 确认删除对话框
    showDeleteConfirm(user) {
      this.$confirm(`确定要删除用户 "${user.username}" 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteUser(user.userId);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    
    // 删除用户
    deleteUser(userId) {
      this.loading = true;
      this.request.delete(`/users/admin/delete/${userId}`)
        .then(res => {
          if (res.code === 1) {
            this.$message.success('删除成功');
            this.fetchUsers();
          } else {
            this.$message.error(res.msg || '删除失败');
          }
        })
        .catch(error => {
          console.error('删除用户失败:', error);
          this.$message.error('删除用户失败');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    // 获取用户列表
    fetchUsers() {
      this.loading = true;
      this.request.get('/users/admin/list')
        .then(res => {
          if (res.code === 1) {
            let data = res.data || [];
            
            // 如果有搜索关键字，进行前端过滤
            if (this.searchText) {
              data = data.filter(user => 
                user.username?.toLowerCase().includes(this.searchText.toLowerCase()) || 
                user.emali?.toLowerCase().includes(this.searchText.toLowerCase())
              );
            }
            
            this.total = data.length;
            
            // 前端分页
            const start = (this.page - 1) * this.pageSize;
            const end = start + this.pageSize;
            this.userList = data.slice(start, end);
          } else {
            this.$message.error(res.msg || '获取用户列表失败');
            this.userList = [];
            this.total = 0;
          }
        })
        .catch(error => {
          console.error('获取用户列表失败:', error);
          this.$message.error('获取用户列表失败');
          this.userList = [];
          this.total = 0;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    // 查看用户详情
    viewUserDetail(userId) {
      this.loading = true;
      this.request.get(`/users/admin/detail/${userId}`)
        .then(res => {
          if (res.code === 1) {
            this.userDetail = res.data;
            this.detailDialogVisible = true;
          } else {
            this.$message.error(res.msg || '获取用户详情失败');
          }
        })
        .catch(error => {
          console.error('获取用户详情失败:', error);
          this.$message.error('获取用户详情失败');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    // 处理每页显示条数变化
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchUsers();
    },
    
    // 处理页码变化
    handleCurrentChange(val) {
      this.page = val;
      this.fetchUsers();
    },
    
    // 搜索用户
    handleSearch() {
      this.page = 1; // 重置页码
      this.fetchUsers();
    },
    
    // 重置搜索
    resetSearch() {
      this.searchText = '';
      this.page = 1;
      this.fetchUsers();
    },

    // 计算年龄
    calculateAge(birthday) {
      if (!birthday) return '未知';
      const today = new Date();
      const birthDate = new Date(birthday);
      let age = today.getFullYear() - birthDate.getFullYear();
      const monthDiff = today.getMonth() - birthDate.getMonth();
      if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
        age--;
      }
      return age;
    }
  },
  created() {
    this.fetchUsers(); // 组件创建时获取用户列表
  }
};
</script>

<style scoped>
.admin-user-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 22px;
  color: #303133;
}

.search-container {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.search-input {
  width: 300px;
  margin-right: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.danger-text {
  color: #F56C6C;
}

.user-detail {
  padding: 0 20px;
}

.user-avatar-container {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.detail-item {
  margin-bottom: 12px;
  display: flex;
}

.detail-label {
  width: 100px;
  color: #909399;
  text-align: right;
  margin-right: 10px;
}

.detail-value {
  color: #303133;
  flex: 1;
}

.avatar-uploader-container {
  display: flex;
  justify-content: center;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}

/* 表格内容垂直居中 */
::v-deep .el-table td {
  padding: 12px 0;
}

/* 卡片样式美化 */
::v-deep .el-table,
::v-deep .el-pagination {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

::v-deep .el-table {
  padding: 20px;
  margin-bottom: 20px;
}

::v-deep .el-pagination {
  padding: 15px 20px;
}
</style>